﻿using System;
using System.Collections;
using System.Collections.Generic;
using FlowCanvas;
using FlowCanvas.Nodes;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.Nodes
{
    public class PlayMultEffects : LatentActionNodeBase
    {
        [Serializable]
        public class Effect
        {
            public int configId;
            public int effectUniqueId;
            public string pointName;
        }

        public BBParameter<List<Effect>> effectConfigs;

        [HideInInspector]
        public FlowOutput onPlay;

        public override bool allowRoutineQueueing { get { return false; } }
        private bool added = false;
        
        public IEnumerator Invoke()
        {
            yield return new WaitForOneFrame();

            if (effectConfigs.value!=null)
            {
                foreach (var effect in effectConfigs.value)
                {
                    BluePrintPoint point = BlueprintUtils.GetBlueprintPoint(effect.pointName);
                    if (point!=null)
                    {
                        BlueprintUtils.PlayEffect(effect.configId,effect.effectUniqueId,point.position,point.eulerAngles);
                        yield return new WaitForOneFrame();
                    }
                }
                OnPlay();
            }
        }

        private void OnPlay()
        {
            added = true;
            onPlay?.Call(new Flow());
        }
        
        protected override void OnRegisterDerivedPorts(FlowNode node)
        {
            onPlay = node.AddFlowOutput("onPlay");
            node.AddFlowInput("In", (f) => { Begin(Invoke(), f); });
        }
        
        public override void OnGraphStoped()
        {
            base.OnGraphStoped();
            if (added)
            {
                if (effectConfigs.value!=null)
                {
                    foreach (var effect in effectConfigs.value)
                    {
                        BlueprintUtils.DestroyEffect(effect.effectUniqueId);
                    }
                }
               
            }
            added = false;
        }
    }
}